package main

import (
	"fmt"
	"github.com/spf13/cobra"
)

func LoadSm2PrivteKey(privKeyFileName, passwd string) error {

	privateKey, err := Read_sm2_private_pem_file(privKeyFileName, passwd)
	if err != nil {
		return err
	}
	fmt.Printf("Private key: %x, pub (%x, %x)\n", privateKey.D, privateKey.X, privateKey.Y)

	return nil
}

func LoadRsaPrivteKey(privKeyFileName, passwd string) error {

	privateKey, err := Read_rsa_private_pem_file(privKeyFileName, passwd)
	if err != nil {
		return err
	}
	fmt.Printf("Private key: D=%x, pub (N=%x, E=%x)\n", privateKey.D, privateKey.N, privateKey.E)

	return nil
}

var loadPrivCmd = &cobra.Command{
	Use:   "loadPriv",
	Short: "从文件中加载私钥测试命令",
	Long: `例如：gmTool.exe loadPriv --private [私钥文件] --pass [私钥文件口令，如果没加密不需要]
	`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("generate key called")

		priFileName, err := cmd.Flags().GetString("private")
		if err != nil {
			fmt.Printf("Error: %v\n", err.Error())
			return
		}
		if len(priFileName) == 0 {
			fmt.Printf("Error: 私钥文件名不能为空\n")
			return
		}
		if !FileExist(priFileName) {
			fmt.Printf("Error: 私钥文件 %v 不存在！\n", priFileName)
			return
		}

		passwd, err := cmd.Flags().GetString("pass")
		if err != nil {
			fmt.Printf("Error: %v\n", err.Error())
			return
		}

		keyType, err := cmd.Flags().GetString("keyType")

		if keyType == "sm2" {
			err = LoadSm2PrivteKey(priFileName, passwd)
			if err != nil {
				fmt.Printf("Error: %v\n", err.Error())
				return
			}
		} else if keyType == "rsa" {
			err = LoadRsaPrivteKey(priFileName, passwd)
			if err != nil {
				fmt.Printf("Error: %v\n", err.Error())
				return
			}
		} else {
			fmt.Printf("未知的密钥类型: %s\n", keyType)
		}
	},
}

func init() {
	rootCmd.AddCommand(loadPrivCmd)

	// Here you will define your flags and configuration settings.
	loadPrivCmd.Flags().StringP("private", "p", "private.pem", "私钥PEM文件名称")
	loadPrivCmd.Flags().StringP("pass", "w", "", "私钥PEM文件口令")
	loadPrivCmd.Flags().StringP("keyType", "t", "sm2", "私钥类型，sm2或rsa，默认为sm2")
}
